import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  factory DatabaseHelper() => _instance;

  static Database? _database;

  DatabaseHelper._internal();

  // 获取数据库实例
  Future<Database?> get database async {
    if (_database != null) return _database;

    _database = await initDatabase();
    return _database;
  }

  // 初始化数据库
  Future<Database> initDatabase() async {
    String path = join(await getDatabasesPath(), 'test_database.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: (Database db, int version) async {
        // 创建数据表
        await db.execute(
          'CREATE TABLE test_table(id INTEGER PRIMARY KEY, name TEXT)',
        );
      },
    );
  }

  // 批量插入数据
  Future<void> insertBatchData(List<Map<String, dynamic>> batchData) async {
    Database? db = await database;
    await db?.transaction((txn) async {
      Batch batch = txn.batch();
      batchData.forEach((data) {
        batch.insert('test_table', data);
      });
      await batch.commit();
    });
  }




  // 查询所有数据
  Future<List<Map<String, dynamic>>?> getAllData() async {
    Database? db = await database;
    return await db?.query('test_table');
  }

  // 删除所有数据
  Future<void> deleteAllData() async {
    Database? db = await database;
    await db?.delete('test_table');
  }

  // 关闭数据库连接
  Future<void> closeDatabase() async {
    Database? db = await database;
    await db?.close();
    _database = null;
  }
}
